package com.bskms.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.bskms.bean.Sign;
import com.bskms.bean.User;
import com.bskms.mapper.UserMapper;
import com.bskms.service.EmailService;
import com.bskms.service.SignAttendanceNotifyService;
import com.bskms.service.SignService;

@Service
public class SignAttendanceNotifyServiceImpl implements SignAttendanceNotifyService {

	private static final Logger logger = LoggerFactory.getLogger(SignAttendanceNotifyServiceImpl.class);

	@Autowired
	private SignService signService;

	@Autowired
	private EmailService emailService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private com.bskms.mapper.ChildrenMapper childrenMapper;

	/**
	 * 每天 08:10 触发一次。
	 */
	@Scheduled(cron = "0 10 8 * * ?")
	public void autoSendTodayOnce() {
		try {
			String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			if (signService.hasSentChildAttendanceReminder(today)) {
				logger.info("{} 学生考勤提醒已发送过，跳过。", today);
				return;
			}
			int sent = sendForDate(today);
			if (sent >= 0) {
				signService.markSentChildAttendanceReminder(today);
				logger.info("{} 学生考勤提醒完成，发送家长数：{}", today, sent);
			}
		} catch (Exception e) {
			logger.error("自动发送学生考勤提醒异常", e);
		}
	}

	@Override
	public void manualSendToday() {
		String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		if (signService.hasSentChildAttendanceReminder(today)) {
			logger.info("{} 学生考勤提醒已发送过，手动触发跳过。", today);
			return;
		}
		int sent = sendForDate(today);
		if (sent >= 0) {
			signService.markSentChildAttendanceReminder(today);
			logger.info("手动触发 {} 学生考勤提醒完成，发送家长数：{}", today, sent);
		}
	}

	@org.springframework.scheduling.annotation.Async
	@Override
	public void manualSendTodayAsync() {
		manualSendToday();
	}

	private int sendForDate(String dateStr) {
		try {
			List<Sign> signs = signService.getChildSignByDate(dateStr);
			Map<String, Sign> childSignMap = new HashMap<>();
			for (Sign s : signs) {
				childSignMap.put(s.getKqrId(), s);
			}

			Set<Integer> allChildIds = new HashSet<>();
			for (com.bskms.bean.Children c : childrenMapper.selectAllChildrenSimple()) {
				allChildIds.add(c.getId());
			}

			int sentCount = 0;
			for (Integer childId : allChildIds) {
				Sign s = childSignMap.get(String.valueOf(childId));
				String status;
				String signTime = null;
				if (s != null) {
					if (s.getState() != null && s.getState() == 3) {
						status = "迟到";
					} else {
						status = "已到校";
					}
					if (s.getSignIn() != null) {
						signTime = new SimpleDateFormat("HH:mm").format(s.getSignIn());
					}
				} else {
					status = "未到校";
				}

				List<User> parents = userMapper.getParentsByChildId(childId);
				if (parents == null || parents.isEmpty()) {
					continue;
				}

				String childName = null;
				try {
					com.bskms.bean.Children child = null;
					for (com.bskms.bean.Children c : childrenMapper.selectAllChildrenSimple()) {
						if (c.getId() != null && c.getId().equals(childId)) { child = c; break; }
					}
					if (child != null) childName = child.getName();
				} catch (Exception ignore) {}
				if (childName == null) childName = "您的孩子";

				for (User p : parents) {
					if (p.getUserMail() == null || p.getUserMail().trim().isEmpty()) continue;
					boolean ok = emailService.sendChildAttendanceEmail(p.getUserMail(), childName, status, signTime);
					if (ok) sentCount++;
				}
			}
			return sentCount;
		} catch (Exception e) {
			logger.error("发送 {} 学生考勤提醒异常", dateStr, e);
			return -1;
		}
	}
}


